import React, { useState, useEffect } from 'react';
import {
  ProForm,
  ProFormText,
  ProFormSelect,
  ProFormDigit,
  ProFormTextArea,
  ProFormDatePicker,
  ProFormDateRangePicker,
  ProFormList,
} from '@ant-design/pro-components';
import { Modal, message } from 'antd';
import { getAvailableContracts } from '@/services/contractChange';

const ContractChangeForm = ({ visible, onCancel, onFinish, initialValues, title }) => {
  const [form] = ProForm.useForm();
  const [contracts, setContracts] = useState([]);
  const [loading, setLoading] = useState(false);
  const [selectedContract, setSelectedContract] = useState(null);

  // 获取合同列表
  useEffect(() => {
    if (visible) {
      fetchContracts();
    }
  }, [visible]);

  // 获取所有正常状态的合同
  const fetchContracts = async () => {
    setLoading(true);
    try {
      const response = await getAvailableContracts({
        current: 1,
        pageSize: 1000, // 获取所有数据
      });

      if (response.success) {
        const contractOptions = response.data?.list?.map(contract => ({
          label: `${contract.customerCode} - ${contract.customerName}`,
          value: contract.id,
          contract: contract,
        })) || [];
        setContracts(contractOptions);
      }
    } catch (error) {
      message.error('获取合同列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 处理合同选择
  const handleContractSelect = (contractId) => {
    const selectedOption = contracts.find(option => option.value === contractId);
    if (selectedOption) {
      const contract = selectedOption.contract;
      setSelectedContract(contract);

      // 自动填充基础信息
      form.setFieldsValue({
        customerCode: contract.customerCode,
        customerName: contract.customerName,
        companyType: contract.companyType,
        area: contract.area,
        contractMonthlyFee: contract.contractMonthlyFee,
        newContractMonthlyFee: contract.contractMonthlyFee, // 默认设置为原合同月收费，用户可以修改
        monthlyFee: contract.monthlyFee,
        newMonthlyFee: contract.monthlyFee, // 默认设置为原月收费，用户可以修改
        // 新增字段的默认值
        contractTerm: contract.contractTerm || 12,
        newContractTerm: contract.contractTerm || 12,
        contractValidPeriod: contract.contractValidPeriod,
        newContractValidPeriod: contract.contractValidPeriod,
        defaultPaymentMethod: contract.defaultPaymentMethod || 'bank',
        newDefaultPaymentMethod: contract.defaultPaymentMethod || 'bank',
        customerRating: contract.customerRating || 'A',
        newCustomerRating: contract.customerRating || 'A',
        serviceItems: contract.serviceItems,
        newServiceItems: contract.serviceItems,
        paymentPeriod: contract.paymentPeriod || 1,
        newPaymentPeriod: contract.paymentPeriod || 1,
        settlementType: contract.settlementType || 'end',
        newSettlementType: contract.settlementType || 'end',
        contractItems: contract.contractItems || [],
        newContractItems: contract.contractItems || [],
      });
    }
  };

  // 重置表单
  useEffect(() => {
    if (visible && !initialValues) {
      form.resetFields();
      setSelectedContract(null);
    } else if (visible && initialValues) {
      // 编辑模式，设置初始值
      form.setFieldsValue(initialValues);
      setSelectedContract(initialValues);
    }
  }, [visible, initialValues, form]);

  return (
    <Modal
      title={title}
      open={visible}
      footer={null}
      onCancel={onCancel}
      width={1000}
      destroyOnClose
    >
      <ProForm
        form={form}
        initialValues={initialValues}
        onFinish={onFinish}
        submitter={{
          resetButtonProps: {
            style: { display: 'none' },
          },
          submitButtonProps: {
            children: '确定',
          },
        }}
        grid
      >
        {/* 合同选择 - 只在新增时显示 */}
        {!initialValues && (
          <ProFormSelect
            name="contractId"
            label="选择合同"
            colProps={{
              span: 24,
            }}
            placeholder="请选择要变更的合同"
            options={contracts}
            rules={[{ required: true, message: '请选择合同' }]}
            fieldProps={{
              loading,
              showSearch: true,
              filterOption: (input, option) =>
                option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0,
              onSelect: handleContractSelect,
            }}
          />
        )}

        <ProForm.Group>
          <ProFormText
            name="customerCode"
            label="客户编号"
            disabled
            placeholder="选择合同后自动填充"
            colProps={{
              span: 12,
            }}
          />
          <ProFormText
            name="customerName"
            label="客户名称"
            disabled
            placeholder="选择合同后自动填充"
            colProps={{
              span: 12,
            }}
          />
        </ProForm.Group>

        <ProForm.Group>
          <ProFormText
            name="companyType"
            label="公司类型"
            disabled
            placeholder="选择合同后自动填充"
            colProps={{
              span: 12,
            }}
          />
          <ProFormText
            name="area"
            label="区域"
            disabled
            placeholder="选择合同后自动填充"
            colProps={{
              span: 12,
            }}
          />
        </ProForm.Group>

        {/* 合同期限 */}
        <ProForm.Group>
          <ProFormDigit
            name="contractTerm"
            label="原合同期限"
            disabled
            fieldProps={{ addonAfter: '月' }}
            placeholder="选择合同后自动填充"
            colProps={{
              span: 12,
            }}
          />
          <ProFormDigit
            name="newContractTerm"
            label="变更后合同期限"
            min={1}
            fieldProps={{ addonAfter: '月' }}
            rules={[{ required: true, message: '请输入变更后的合同期限' }]}
            placeholder="请输入变更后的合同期限"
            colProps={{
              span: 12,
            }}
          />
        </ProForm.Group>

        {/* 合同有效期 */}
        <ProForm.Group>
          <ProFormDateRangePicker
            name="contractValidPeriod"
            label="原合同有效期"
            disabled
            placeholder={['开始日期', '结束日期']}
            colProps={{
              span: 12,
            }}
          />
          <ProFormDateRangePicker
            name="newContractValidPeriod"
            label="变更后合同有效期"
            rules={[{ required: true, message: '请选择变更后的合同有效期' }]}
            placeholder={['开始日期', '结束日期']}
            colProps={{
              span: 12,
            }}
          />
        </ProForm.Group>

        {/* 默认收款方式 */}
        <ProForm.Group>
          <ProFormSelect
            name="defaultPaymentMethod"
            label="原默认收款方式"
            disabled
            options={[
              { label: '银行转账', value: 'bank' },
              { label: '现金', value: 'cash' },
              { label: '支付宝', value: 'alipay' },
              { label: '微信', value: 'wechat' },
            ]}
            placeholder="选择合同后自动填充"
            colProps={{
              span: 12,
            }}
          />
          <ProFormSelect
            name="newDefaultPaymentMethod"
            label="变更后默认收款方式"
            options={[
              { label: '银行转账', value: 'bank' },
              { label: '现金', value: 'cash' },
              { label: '支付宝', value: 'alipay' },
              { label: '微信', value: 'wechat' },
            ]}
            rules={[{ required: true, message: '请选择变更后的默认收款方式' }]}
            placeholder="请选择变更后的默认收款方式"
            colProps={{
              span: 12,
            }}
          />
        </ProForm.Group>

        {/* 客户评级 */}
        <ProForm.Group>
          <ProFormSelect
            name="customerRating"
            label="原客户评级"
            disabled
            options={[
              { label: 'A+', value: 'A+' },
              { label: 'A', value: 'A' },
              { label: 'B+', value: 'B+' },
              { label: 'B', value: 'B' },
              { label: 'C', value: 'C' },
            ]}
            placeholder="选择合同后自动填充"
            colProps={{
              span: 12,
            }}
          />
          <ProFormSelect
            name="newCustomerRating"
            label="变更后客户评级"
            options={[
              { label: 'A+', value: 'A+' },
              { label: 'A', value: 'A' },
              { label: 'B+', value: 'B+' },
              { label: 'B', value: 'B' },
              { label: 'C', value: 'C' },
            ]}
            rules={[{ required: true, message: '请选择变更后的客户评级' }]}
            placeholder="请选择变更后的客户评级"
            colProps={{
              span: 12,
            }}
          />
        </ProForm.Group>

        {/* 合同服务项目 */}
        <ProForm.Group>
          <ProFormText
            name="serviceItems"
            label="原合同服务项目"
            disabled
            placeholder="选择合同后自动填充"
            colProps={{
              span: 12,
            }}
          />
          <ProFormText
            name="newServiceItems"
            label="变更后合同服务项目"
            placeholder="请输入变更后的服务项目，用逗号分隔"
            rules={[{ required: true, message: '请输入变更后的服务项目' }]}
            colProps={{
              span: 12,
            }}
          />
        </ProForm.Group>

        {/* 收款周期 */}
        <ProForm.Group>
          <ProFormDigit
            name="paymentPeriod"
            label="原收款周期"
            disabled
            fieldProps={{ addonAfter: '期' }}
            placeholder="选择合同后自动填充"
            colProps={{
              span: 12,
            }}
          />
          <ProFormDigit
            name="newPaymentPeriod"
            label="变更后收款周期"
            min={1}
            fieldProps={{ addonAfter: '期' }}
            rules={[{ required: true, message: '请输入变更后的收款周期' }]}
            placeholder="请输入变更后的收款周期"
            colProps={{
              span: 12,
            }}
          />
        </ProForm.Group>

        {/* 结算方式 */}
        <ProForm.Group>
          <ProFormSelect
            name="settlementType"
            label="原结算方式"
            disabled
            options={[
              { label: '期初', value: 'start' },
              { label: '期末', value: 'end' },
            ]}
            placeholder="选择合同后自动填充"
            colProps={{
              span: 12,
            }}
          />
          <ProFormSelect
            name="newSettlementType"
            label="变更后结算方式"
            options={[
              { label: '期初', value: 'start' },
              { label: '期末', value: 'end' },
            ]}
            rules={[{ required: true, message: '请选择变更后的结算方式' }]}
            placeholder="请选择变更后的结算方式"
            colProps={{
              span: 12,
            }}
          />
        </ProForm.Group>

        {/* 合同月收费 */}
        <ProForm.Group>
          <ProFormDigit
            name="contractMonthlyFee"
            label="原合同月收费"
            disabled
            fieldProps={{
              addonAfter: '元',
              formatter: (value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ','),
            }}
            placeholder="选择合同后自动填充"
            colProps={{
              span: 12,
            }}
          />
          <ProFormDigit
            name="newContractMonthlyFee"
            label="变更后合同月收费"
            min={0}
            fieldProps={{
              addonAfter: '元',
              formatter: (value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ','),
              parser: (value) => value.replace(/\$\s?|(,*)/g, ''),
            }}
            rules={[{ required: true, message: '请输入变更后的合同月收费' }]}
            placeholder="请输入变更后的合同月收费"
            colProps={{
              span: 12,
            }}
          />
        </ProForm.Group>

        {/* 月收费 */}
        <ProForm.Group>
          <ProFormDigit
            name="monthlyFee"
            label="原月收费"
            disabled
            fieldProps={{
              addonAfter: '元',
              formatter: (value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ','),
            }}
            placeholder="选择合同后自动填充"
            colProps={{
              span: 12,
            }}
          />
          <ProFormDigit
            name="newMonthlyFee"
            label="变更后月收费"
            min={0}
            fieldProps={{
              addonAfter: '元',
              formatter: (value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ','),
              parser: (value) => value.replace(/\$\s?|(,*)/g, ''),
            }}
            rules={[{ required: true, message: '请输入变更后的月收费' }]}
            placeholder="请输入变更后的月收费"
            colProps={{
              span: 12,
            }}
          />
        </ProForm.Group>

        {/* 合同明细 */}
        <ProFormList
          name="newContractItems"
          label="变更后合同明细"
          creatorButtonProps={{
            creatorButtonText: '添加合同明细',
          }}
          colProps={{
            span: 24,
          }}
          itemContainerRender={(doms) => {
            return <ProForm.Group colProps={{ span: 24 }}>{doms}</ProForm.Group>;
          }}
        >
          <ProFormText
            name="monthlyFee"
            label="合同月收费"
            colProps={{
              span: 8,
            }}
            rules={[{ required: true, message: '请输入合同月收费' }]}
            placeholder="请输入月收费金额"
          />
          <ProFormDateRangePicker
            name="servicePeriod"
            label="服务期间"
            rules={[{ required: true, message: '请选择服务期间' }]}
            placeholder={['开始日期', '结束日期']}
            colProps={{
              span: 8,
            }}
          />
          <ProFormText
            name="totalPrice"
            label="服务总价"
            rules={[{ required: true, message: '请输入服务总价' }]}
            placeholder="请输入服务总价"
            colProps={{
              span: 8,
            }}
          />
        </ProFormList>

        <ProFormTextArea
          name="changeReason"
          label="变更原因"
          placeholder="请详细说明合同变更的原因"
          rules={[{ required: true, message: '请输入变更原因' }]}
          fieldProps={{
            rows: 4,
          }}
          colProps={{
            span: 24,
          }}
        />
      </ProForm>
    </Modal>
  );
};

export default ContractChangeForm; 